import React, { useEffect, useState } from 'react'
import withAuth from '../../hooks/withAuth'
import { Button, Space, Table, Checkbox, Form, Input, message, Popconfirm, Modal } from 'antd';
import request from "../../api/request";
import Search from '../../components/Search';

function Home() {
    const [data, setData] = useState([])
    const [page, setPage] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    const [total, setTotal] = useState(1);
    const [keyword, setKeyword] = useState('');
    const [searchForm] = Form.useForm();
    const [title, setTitle] = useState('');
    const [addFrom] = Form.useForm();
    const [editId, setEdit] = useState('');

    const getData = async () => {
        const res = await request.get('/article/list', {
            params: {
                page,
                pageSize,
                keyword
            }
        })
        console.log(res)
        setData(res.data.rows)
        setTotal(res.data.count)
    }
    useEffect(() => {
        getData()
    }, [page, pageSize, keyword])
    //分页
    const change = function (page, pageSize) {
        setPage(page);
        setPageSize(pageSize);
    }
    //搜索
    const onFinish = values => {
        console.log('Success:', values);
        setKeyword(values.keyword)
    };
    const onFinishFailed = errorInfo => {
        console.log('Failed:', errorInfo);
    };
    //重置
    const reset = () => {
        searchForm.resetFields()
        setKeyword("");
    }
    //删除
    const confirm = (id) => {
        message.success('删除成功');
        console.log(id);
        const newArr = data.filter((item) => item.id != id)
        setData(newArr);
    };
    const cancel = e => {
        console.log(e);
        message.error('Click on No');
    };
    //新增编辑表单
    const Finish = values => {
        console.log('Success:', values);
        if (title === "新增信息") {
            request.post('/article',
                {
                    title: values.title,//文章标题
                    content: values.content,//文章内容
                    tagList: ["HTTP"],//标签  array[string]
                    categoryList: ["HTTP"],//分类  array[string]
                    authorId: 47529555//用户id 暂时写死47529555 登陆成功后返回的用户信息

                },
                {
                    headers: {
                        Authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Imp5a2wiLCJ1c2VySWQiOjQ3NTI5NTU1LCJyb2xlIjoxLCJpYXQiOjE3Mzk3OTQyNDIsImV4cCI6MTc0MjM4NjI0Mn0.O7KlsogMjr6YowtOXKGrEaldz5kjKHWQCn3FGvRd1bA',
                    }
                }
            ).then((res) => {
                console.log('add', res)
                setIsModalOpen(false);
                alert("新增成功")
            })
        }
        else {
            request.put(`/article/${editId}`,
                {
                    title: values.title,//文章标题
                    content: values.content,//文章内容
                    tagList: ["HTTP"],//标签  array[string]
                    categoryList: ["HTTP"],//分类  array[string]
                },
                {
                    headers:{
                        Authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Imp5a2wiLCJ1c2VySWQiOjQ3NTI5NTU1LCJyb2xlIjoxLCJpYXQiOjE3MzU1NDg3ODksImV4cCI6MTczODE0MDc4OX0.QgKf6srco9KYjIPGmf_7MH-TtgF5FUP9_ssYudDqR8k',
                    }
                }
            ).then((res)=>{
                console.log('edut', res)
                setIsModalOpen(false);
                alert("编辑成功")
            })
        }
    };
    const FinishFailed = errorInfo => {
        console.log('Failed:', errorInfo);
    };
    //新增
    const [isModalOpen, setIsModalOpen] = useState(false);
    const handleOk = () => {
        setIsModalOpen(false);
    };
    const handleCancel = () => {
        setIsModalOpen(false);
    };
    const add = () => {
        setIsModalOpen(true);
        setTitle("新增信息");
        addFrom.resetFields();
    };
    //编辑
    const edit = (record) => {
        setIsModalOpen(true);
        setTitle("编辑信息");
        setEdit(record.id)
        addFrom.setFieldsValue(record)
    }
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
        },
        {
            title: '标题',
            dataIndex: 'title',
            key: 'title',
            render: text => <a>{text}</a>,
        },
        {
            title: '文章内容',
            dataIndex: 'content',
            key: 'content',
        },
        {
            title: '发布时间',
            dataIndex: 'createdAt',
            key: 'createdAt',
        },
        {
            title: '更新时间',
            dataIndex: 'updatedAt',
            key: 'updatedAt',
        },
        {
            title: '操作栏',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Button onClick={() => edit(record)}>编辑</Button>
                    <Button>查看</Button>
                    <Popconfirm
                        title="删除框"
                        description="你确定要删除嘛?"
                        onConfirm={() => confirm(record.id)}
                        onCancel={cancel}
                        okText="确认"
                        cancelText="取消"
                    >
                        <Button>删除</Button>
                    </Popconfirm>
                </Space>
            ),
        },
    ];
    return (
        <div>
            {/* 搜索 */}
            <Search searchForm={searchForm} onFinish={onFinish} onFinishFailed={onFinishFailed} reset={reset}></Search>
            {/* 新增编辑弹框 */}
            <Button type="primary" onClick={() => add()}>新增</Button>
            <Modal title={title} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                <Form
                    form={addFrom}
                    name="basic"
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                    style={{ maxWidth: 600 }}
                    initialValues={{ remember: true }}
                    onFinish={Finish}
                    onFinishFailed={FinishFailed}
                    autoComplete="off"
                >
                    <Form.Item
                        label="标题"
                        name="title"
                        rules={[{ required: true, message: 'Please input your title!' }]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="文章内容"
                        name="content"
                        rules={[{ required: true, message: 'Please input your content!' }]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item name="remember" valuePropName="checked" label={null}>
                        <Checkbox>Remember me</Checkbox>
                    </Form.Item>

                    <Form.Item label={null}>
                        <Button type="primary" htmlType="submit">
                            Submit
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>
            <Table columns={columns} dataSource={data}
                pagination={{
                    total: total,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    showTotal: total => `Total ${total} items`,
                    onChange: change
                }}
            />
        </div>
    )
}

export default withAuth(Home)
